package com.envy.handler;

import com.envy.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginHandler implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        User user = (User)httpServletRequest.getSession().getAttribute("USER");
        if(user==null){
            System.out.println("1、interceptor*****preHandle");
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login");
//            httpServletResponse.sendRedirect("../login");  //或者是下面这种方式
            return false;
        }
        return true; //如果这个方法返回false，则表明后续操作不会进行
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("3、interceptor*****postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("4、interceptor*****afterCompletion");
    }
}
